/*
 * Copyright (c) 2015 DHC Corporation.
 */
package cn.com.dhc.danlu.util;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.util.List;

/**
 * Context用共通方法
 *
 * @author MuWei
 * @version 1.00 2015/02/03 新建
 */
public class ContextUtils {

    /**
     * 退出程序
     *
     * @param context
     *         Context
     */
    public static void destroy (Context context) {
        try {
            // 退出丹露App进程
            killProcess (context, context.getPackageName ());
        } catch (Exception e) {
            Log.e ("ContextUtils", e.toString ());
        }
    }

    /**
     * Kill process
     */
    private static void killProcess (Context context, String packageName) {
        int version = android.os.Build.VERSION.SDK_INT;
        ActivityManager manager = (ActivityManager) context
                .getSystemService (Context.ACTIVITY_SERVICE);
        if (version <= 7) {
            manager.restartPackage (packageName);
        } else {
            List<ActivityManager.RunningAppProcessInfo> process = manager
                    .getRunningAppProcesses ();
            int len = process.size ();
            for (int i = 0; i < len; i++) {
                if (process.get (i).processName.equals (packageName)) {
                    android.os.Process.killProcess (process.get (i).pid);
                }
            }
        }
    }

    /**
     * Helper Method to Test if external Storage is Available
     */
    public static boolean isExternalStorageAvailable () {
        boolean state = false;
        String extStorageState = Environment.getExternalStorageState ();
        if (Environment.MEDIA_MOUNTED.equals (extStorageState)) {
            state = true;
        }
        return state;
    }

    /**
     * Helper Method to Test if external Storage is read only
     */
    public static boolean isExternalStorageReadOnly () {
        boolean state = false;
        String extStorageState = Environment.getExternalStorageState ();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals (extStorageState)) {
            state = true;
        }
        return state;
    }
}